package com.tange.ai.iot.client.gnssa.utils;

import android.os.Build;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Base64;

public class VrThumbnailReceiver {

    // 常量定义
    public static final int THUMBNAIL_SIZE = 256;
    public static final int MAX_THUMBNAILS = 50;

    // 缩略图结构
    public static class VrThumbnailJpeg {
        public int size;
        public int timestamp;

        @JsonInclude(JsonInclude.Include.NON_NULL)
        public byte[] data; // 原始二进制数据

        @JsonInclude(JsonInclude.Include.NON_NULL)
        public String data_base64; // Base64 编码版本

        public VrThumbnailJpeg(ByteBuffer buffer, boolean includeRawData) {
            size = buffer.getInt();
            timestamp = buffer.getInt();

            if (includeRawData) {
                data = new byte[THUMBNAIL_SIZE];
                buffer.get(data);
            } else {
                buffer.position(buffer.position() + THUMBNAIL_SIZE); // 跳过数据
            }
        }
    }

    // 响应结构
    public static class HyVrThumbnailResp {
        public int num;
        public VrThumbnailJpeg[] jpegs;

        public HyVrThumbnailResp(byte[] rawData, boolean includeRawData) {
            ByteBuffer buffer = ByteBuffer.wrap(rawData);
            buffer.order(ByteOrder.LITTLE_ENDIAN); // 根据C端设置字节序

            // 读取缩略图数量
            num = Math.min(buffer.getInt(), MAX_THUMBNAILS);
            jpegs = new VrThumbnailJpeg[MAX_THUMBNAILS];

            // 读取每个缩略图
            for (int i = 0; i < MAX_THUMBNAILS; i++) {
                jpegs[i] = new VrThumbnailJpeg(buffer, includeRawData);
            }
        }
    }

    // 将响应对象转为 JSON
    public static String toJson(HyVrThumbnailResp response, boolean includeRawData, boolean includeBase64) {
        try {
            // 如果需要 Base64 编码
            if (includeBase64 && response.jpegs != null) {
                for (VrThumbnailJpeg jpeg : response.jpegs) {
                    if (jpeg.data != null) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            jpeg.data_base64 = Base64.getEncoder().encodeToString(jpeg.data);
                        }
                    }
                }
            }

            // 如果不包含原始数据，清除字段
            if (!includeRawData) {
                for (VrThumbnailJpeg jpeg : response.jpegs) {
                    jpeg.data = null;
                }
            }

            ObjectMapper mapper = new ObjectMapper();
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response);
        } catch (Exception e) {
            throw new RuntimeException("JSON conversion failed", e);
        }
    }
}
